package cn.edu.ctbu.dp01.service;

import cn.edu.ctbu.dp01.constent.REnum;
import cn.edu.ctbu.dp01.dao.TeacherRepository;
import cn.edu.ctbu.dp01.entity.Teacher;
import cn.edu.ctbu.dp01.exception.RException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;

@Service
public class TeacherService {

    @Autowired
    public TeacherRepository teacherRepository;

    /**
     * 读所有的学生列表
     * @return List Student
     */
    public List<Teacher> getAll(){

        return teacherRepository.findAll();

    }

    /**
     * 用id进行查询
     * @param id 主键，整数
     * @return
     */
    public Teacher findById(Integer id){


        return teacherRepository.findById(id).get();
    }

    /**
     * 按名字进行查询，Like
     * @param name
     * @return
     */
    public List<Teacher> findByName(String name){
        return teacherRepository.findByNameLike(name);
    }
    /**
     * 按名字和密码进行查询
     * @param name
     * @param password
     * @return
     */
    public List<Teacher> findByNameAndPassword(String name, String password){
        return teacherRepository.findByNameAndPassword(name, password);
    }
    public  void insert(Teacher teacher){
        teacherRepository.save(teacher);
    }
    // 更新学生信息
    public Teacher update(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    // 删除学生
    public void delete(Integer id) {
        teacherRepository.deleteById(id);
    }

    public Teacher add(Teacher teacher) {
        return teacherRepository.save(teacher);
    }
    public Teacher validateUsernameAndPassword(String tno, String password) throws Exception{
        List<Teacher> teachers=teacherRepository.findByTno(tno);
        if(teachers.size()>0){
            Teacher teacher=teachers.get(0);
            if(teacher.getPassword().equals(password)){
                //成功
                return teacher;
            }else{
                throw new RException(REnum.LOGIN_ERR);
            }
        }else {
            throw new RException(REnum.LOGIN_ERR);
        }
    }
    public Page<Teacher> getAll(Pageable pageable){
        return teacherRepository.findAll(pageable);
    }
    public Page<Teacher> getAll(Example<Teacher> example,Pageable pageable){
        return teacherRepository.findAll(example,pageable);
    }
}
